package modes

import (
	"fmt"
)

type LiveType struct {
	Id        int64     `json:"liv_id" xorm:"id"`            //id
	PId       int64     `json:"liv_pid" xorm:"pid"`          //项目id
	SId       int64     `json:"liv_sid" xorm:"sid"`          //科目id
	LiveName  string    `json:"live_name" xorm:"live_name"`  //直播课程类型名称
	LiveState int64     `json:"liv_state" xorm:"live_state"` //状态 0正常 1 禁用
	SName     []Subject `json:"s_name" xorm:"-"`             //科目名称
}

func (this *LiveType) TableName() string {
	return "livetype"
}

func (this *LiveType) Save() (int64, error) {

	return Db(1).Insert(this)
}

func (this *LiveType) Get() (bool, error) {
	return Db(1).Get(this)
}
func (this *LiveType) delete(where string) (int64, error) {
	return Db(1).Where(where).Delete(this)
}
func (this *LiveType) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *LiveType) Count(where string) (int64, error) {
	var val LiveType
	return Db(1).Where(where).Count(&val)
}
func (this *LiveType) update(where string, field string) (int64, error) {
	return Db(1).Where(where).Cols(field).Update(this)
}

func (this *LiveType) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *LiveType) where(fage, count, page int, where, field string) ([]LiveType, error) {
	list := make([]LiveType, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(1).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(1).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}

type PSLive struct {
	LiveType `json:"type" xorm:"extends"`
	Project  `json:"pro" xorm:"extends"`
}

func (this *PSLive) Lookups(val *Pager) error {
	list := make([]PSLive, 0)
	val.TName = "livetype"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.id", val.TName) // id
	case 1:
		field = fmt.Sprintf("%s.pid", val.TName) // 项目
	case 2:
		field = fmt.Sprintf("%s.sid", val.TName) // 科目
	default:
		field = fmt.Sprintf("%s.id", val.TName) // id
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	val.Total, _ = Db(1).Table(val.TName).Where(val.ToWhere()).Count(this)
	err := Db(1).Table(val.TName).
		Join("LEFT", "project", fmt.Sprintf("%s.pid = project.id", val.TName)).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
		for i, row := range list {
			list[i].SName, _ = GetSname(row.SId)
		}
		val.List = list
	}
	fmt.Println(list)
	return err
}

func GetSname(sid int64) ([]Subject, error) {
	list := make([]Subject, 0)
	w := fmt.Sprintf("id = %d", sid)
	err := Db(0).Where(w).Find(&list)
	return list, err
}
